package cs.upt.awp.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import cs.upt.awp.data.City;
import cs.upt.awp.data.Country;
import cs.upt.awp.data.TravelNote;
import cs.upt.awp.data.TravelRecord;

public class TravelRecordsDAO implements DataDAO<TravelRecord> {

	@Autowired
	SessionFactory sessionFactory;

	Session session = null;
	Transaction tx = null;

	@Override
	public boolean addEntity(TravelRecord record) throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		session.save(record);
		tx.commit();
		session.close();
		return false;
	}
	
	public boolean updateEntity(TravelRecord record) throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		TravelRecord trecord = (TravelRecord) session.load(
				TravelRecord.class, new Long(record.getId()));
		
		trecord.setCity((City) session.load(City.class, new Long(record.getCity().getId())));
		trecord.setCountry((Country) session.load(Country.class, record.getCountry().getCode()));
		trecord.setEndDate(record.getEndDate());
		trecord.setStartDate(record.getStartDate());
		session.save(trecord);
		tx.commit();
		session.close();
		return false;
	}

	@Override
	public TravelRecord getEntityById(long id) throws Exception {
		session = sessionFactory.openSession();
		TravelRecord record = (TravelRecord) session.load(
				TravelRecord.class, new Long(id));
		tx = session.getTransaction();
		session.beginTransaction();
		tx.commit();
		//session.close();
		return record;
	}

	public List<TravelRecord> getUserRecords(String userName) throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();		
	//	System.out.println("TravelRecordsDAO userName: " + userName);
		Query q = session.createQuery("select tr from travelrecords tr where tr.user.userName = :userName"); 
		q.setString("userName", userName);
		List<TravelRecord> records = q.list();
		tx.commit();
		session.close();
		return records;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TravelRecord> getEntityList() throws Exception {
		session = sessionFactory.openSession();
		tx = session.beginTransaction();
		List<TravelRecord> recordsList = session.createCriteria(
				TravelRecord.class).list();
		tx.commit();
		session.close();
		return recordsList;
	}

	@Override
	public boolean deleteEntity(long id) throws Exception {
		session = sessionFactory.openSession();
		Object o = session.load(TravelRecord.class, id);
		tx = session.getTransaction();
		session.beginTransaction();
		session.delete(o);
		tx.commit();
		session.close();
		return false;
	}

}
